<template>
  <div class="page-editor editor-wrapper" v-loading="loading">
    <!--左侧导航-->
    <div class="editor-side-bar border-R">
      <el-tabs tab-position="left" v-model="activeSideBar" style="height: 100%;">
        <template v-for="(item, index) in sidebarMenus">
          <el-tab-pane :name="item.value"  :key="index" v-if="!item.pageMode || (item.pageMode && item.pageMode === pageMode)">
            <el-tooltip slot="label" class="item" effect="dark" :content="item.label" placement="right">
              <i :class="item.elementUiIcon"></i>
            </el-tooltip>
          </el-tab-pane>
        </template>
      </el-tabs>
    </div>
    <!--组件&页面&模板-->
    <div class="editor-page-edit-wrapper">
      <componentLibs v-if="activeSideBar === 'componentLibs'" :componentsList="componentsList"/>
      <templateLibs v-if="activeSideBar === 'templateLibs'"/>
    </div>
    <!--页面编辑区域-->
    <div class="editor-main">
      <div class="control-bar-wrapper">
        <controlBar
                :scale.sync="canvasConfig.scale"
                @showPreview="showPreviewFn"
                @cancel="cancelFn"
                @publish="publishFn"
                @save="saveFn"/>
      </div>
      <editorPan :scale.sync="canvasConfig.scale"/>
    </div>
    <!--属性编辑区域-->
    <div class="el-attr-edit-wrapper scrollbar-wrapper">
      <el-tabs v-model="activeAttr" stretch>
        <el-tab-pane label="属性" name="属性">
          <attrEdit></attrEdit>
        </el-tab-pane>
<!--        <el-tab-pane label="事件" name="事件">-->
<!--          <eventEdit></eventEdit>-->
<!--        </el-tab-pane>-->
<!--        <el-tab-pane label="动画" name="动画">-->
<!--          <animationEdit></animationEdit>-->
<!--        </el-tab-pane>-->
<!--        <el-tab-pane label="JS脚本" name="脚本">-->
<!--          <scriptEdit></scriptEdit>-->
<!--        </el-tab-pane>-->
        <el-tab-pane label="页面设置" name="页面属性">
          <pageAttrEdit></pageAttrEdit>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!--预览-->
    <previewPage
            v-if="showPreview"
            :pageData="projectData"
            :pageId="id"
            @closePreview="showPreview = false"
            @publishFn="publishFn"
            @saveFn="saveFn"></previewPage>
    <!--我的图片-->
  </div>
</template>

<script>
	import componentLibs from './components/component-libs/Index'
	import templateLibs from './components/template-libs'
	import editorPan from './components/editor-panel/Index'
    import eleConfig from './ele-config'
	// 属性编辑相关组件
	import attrEdit from './components/attr-configure/attr-edit'
	import pageAttrEdit from './components/attr-configure/page-attr-edit'

	import controlBar from './components/control-bar'

	import previewPage from './components/preview'

	import {mapState, mapGetters} from 'vuex'
	import html2canvas from 'html2canvas'

    import {
      update,
      getDetail,
    } from "@/api/cms/pageInfo";
	export default {
		components: {
			componentLibs,
			templateLibs,
			editorPan,
			attrEdit,
			pageAttrEdit,
			controlBar,
			previewPage
		},
		data() {
			return {
              componentsList: eleConfig,
              id: '', // 当前页面id
              loading: false,
              showPreview: false,
              activeAttr: '属性',
              activeSideBar: 'componentLibs',
              sidebarMenus: [
                {
                  label: '组件列表',
                  value: 'componentLibs',
                  elementUiIcon: 'el-icon-s-operation'
                },
                {
                  label: '模板库',
                  value: 'templateLibs',
                  elementUiIcon: 'el-icon-files'
                }
              ],
              canvasConfig: {
                scale: 1
              }
			}
		},
		computed: {
			...mapState({
				projectData: state => state.editor.projectData,
			}),
			...mapGetters([
				'pageMode'
			])
		},
		created() {
			this.$store.dispatch('setPrjectData')
			this.id = this.$route.query.id;
			this.initPageData();
		},
      methods: {
        /**
         * 初始化页面数据
         */
        initPageData() {
          var jsonstr = {
            "coverImage":"",
            "pageMode":"h5",
            "width":375,
            "height":644,
            "elements":[],
            "commonStyle":{
              "backgroundColor":"",
              "backgroundImage":"",
              "backgroundSize":"cover"
            }
          };
          getDetail(this.id).then(res=>{
            if(res.data.data.layoutJson){
              jsonstr = JSON.parse(res.data.data.layoutJson);
            }
            this.$store.dispatch('setPrjectData', {
              ...jsonstr
            })
          })
        },
        /**
         * 保存
         */
        async saveFn() {
          // 提交数据再预览
          update({id:this.id,layoutJsonTemp:JSON.stringify(this.projectData)}).then(res=>{
            this.$message({message:"保存成功",type:"primary"});
          })
        },
        /**
         * 保存
         */
        async publishFn() {
          update({id:this.id,layoutJson:JSON.stringify(this.projectData)}).then(res=>{
            this.$message({message:"保存成功",type:"primary"});
          })
        },
        async showPreviewFn() {
          update({id:this.id,layoutJsonTemp:JSON.stringify(this.projectData)}).then(res=>{
            this.showPreview = true;
          })
        },
        /**
         * 退出
         */
        cancelFn() {
          this.$confirm('确认退出编辑?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$router.push('/page-list')
          }).catch(() => {})
        },
        /**
         * 提供截屏作为项目主图
         */
        screenshots() {
          const el = document.querySelector("#canvas-panel")
          return new Promise((resolve, reject) => {
            html2canvas(el).then(canvas => {
              const dataUrl = canvas.toDataURL('image/jpeg', 0.6)
              const blob = this.$mUtils.dataURItoBlob(dataUrl)
              const file = new window.File([blob], +new Date() + '.png', {type: 'image/png'})
              let params = new FormData()
              params.append('file', file);
              this.$axios.post('/common/uploadFile', params).then(res => {
                // 替换主图链接
                this.projectData.coverImage = res.body;
                resolve(res.body)
              }).catch(err => {
                reject(err)
              })
            })
          })
        },
      }
	}
</script>

<style lang="scss" scoped>
  .editor-wrapper {
    display: flex;
    height: 100%;
    position: relative;
    .editor-side-bar {
      width: 55px;
    }
    .editor-page-edit-wrapper {
      width: 210px;
      padding: 0 1px;
    }
    .editor-main {
      flex: 1;
      background: #f0f2f5;
      position: relative;
    }
    .el-attr-edit-wrapper {
      width: 380px;
      padding: 0;
    }
  }

  .control-bar-wrapper {
    /*position: absolute;*/
    /*top: 0px;*/
    /*left: 0;*/
    /*z-index: 1000;*/
    height: 44px;
    width: 100%;
    background: #fff;
    text-align: center;
  }
</style>
<style lang="scss">
  .editor-side-bar {
    .el-tabs__item.is-active {
      background: rgba(37, 165, 137, 0.09);
    }
  }

  .el-attr-edit-wrapper {
    .el-tabs {
      height: 100%;
      padding-left: 16px;
      padding-right: 16px;
      padding-bottom: 10px;
    }
    .el-tabs__content {
      height: calc(100% - 55px);
      & > div {
        height: 100%;
      }
      .attr-edit-inner {
        padding-left: 16px;
        padding-right: 16px;
      }
    }
  }
</style>
